package com.niannian.activity;

import java.io.File;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.niannian.BaseActivity;
import com.niannian.MyApplication;
import com.niannian.R;
import com.niannian.imgCache.core.BitmapDecoder;
import com.niannian.photo.ViewPagerFixed;
import com.niannian.util.BitmapUtil;
import com.niannian.util.Common;
import com.niannian.util.FileUtils;
import com.niannian.util.MD5Util;
import com.niannian.util.network.QHttpUtil;
import com.niannian.view.PhotoViewAttacher;
import com.niannian.view.PhotoViewAttacher.OnViewTapListener;
import com.niannian.view.ViewPagerScroller;

/**
 * 多图滑动显示
 * 
 * @author shenglin
 * 
 */
public class MorePicShow extends BaseActivity {

	String picurl = "";
	int picnum = 0;// 图片数，
	int curpic = 0;

	private ArrayList<View> listViews = null;// 视图
	private ArrayList<ImageView> listImaViews = null;// 视图里面的图片
	private ArrayList<ProgressBar> progressBar = null;// 视图里面的加载进度
	private ArrayList<String> picurList = null;// 图片地址
	private ViewPagerFixed pager;
	private MyPageAdapter adapter;
	TextView tv_pic_num;
	private Map<Integer, String> DownloadingMap = new HashMap<Integer, String>();// 正在下载中的

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_more_pic_show);
		initView();
	}

	ViewPager viewpage;

	private void initView() {
		picurl = getIntent().getStringExtra("display");
		picnum = getIntent().getIntExtra("picnum", 0);
		curpic = getIntent().getIntExtra("curpic", 0);

		pager = (ViewPagerFixed) findViewById(R.id.gallery01);

		pager.setOnPageChangeListener(pageChangeListener);

		tv_pic_num = (TextView) findViewById(R.id.tv_pic_num);

		tv_pic_num.setText(curpic + 1 + "/" + picnum);

		initImagesSmall();

		adapter = new MyPageAdapter(listViews);

		pager.setAdapter(adapter);
		pager.setPageMargin((int) getResources().getDimensionPixelOffset(R.dimen.ui_10_dip));

		pager.setCurrentItem(curpic);
		initImagesBig(curpic);
		adapter.notifyDataSetChanged();
		initViewPagerScroll();
	}

	private void initViewPagerScroll() {
		try {
			Field mScroller = null;
			mScroller = ViewPager.class.getDeclaredField("mScroller");
			mScroller.setAccessible(true);
			ViewPagerScroller scroller = new ViewPagerScroller(pager.getContext());
			mScroller.set(pager, scroller);
		} catch (NoSuchFieldException e) {

		} catch (IllegalArgumentException e) {

		} catch (IllegalAccessException e) {

		}
	}

	private void initImagesSmall() {
		String picPath = picurl.substring(0, picurl.length() - 4);
		if (picnum == 1) {
			initListViews(picurl);
		} else {
			for (int i = 0; i < picnum; i++) {
				if (i == 0) {
					initListViews(picurl);
				} else {
					initListViews(picPath + "_" + i + ".jpg");
				}
			}
		}

	}

	private void initImagesBig(int p) {

		String imDUrl = Common.getPublicImagesBigUrl(picurList.get(p));
		String LimDUrl = MyApplication.FILE_PATH_TEMP + MD5Util.encode(imDUrl) + FileUtils.getImageFileExtension(imDUrl);
		File sdimage = new File(LimDUrl);
		if (!sdimage.exists()) {
			progressBar.get(p).setVisibility(View.VISIBLE);

			if (!DownloadingMap.containsKey(p)) {
				DownloadingMap.put(p, "");
				new downloadImage(p).execute(imDUrl);
			}

		} else {
			progressBar.get(p).setVisibility(View.GONE);
			PhotoViewAttacher mAttacher = null;
			try {
				byte[] data = FileUtils.getBytes(sdimage);
				Bitmap showBitmap = BitmapDecoder.decodeSampledBitmapFromByteArray(data, 0, data.length, mScreenWidth, mScreenHeight);
				listImaViews.get(p).setImageBitmap(showBitmap);
				mAttacher = new PhotoViewAttacher((listImaViews.get(p)));
			} catch (Exception e) {
				e.printStackTrace();
			}
			mAttacher.setOnViewTapListener(new OnViewTapListener() {
				@Override
				public void onViewTap(View view, float x, float y) {
					finish();
				}
			});
		}
		adapter.notifyDataSetChanged();
	}

	private void initListViews(String url) {
		if (listViews == null)
			listViews = new ArrayList<View>();
		if (listImaViews == null)
			listImaViews = new ArrayList<ImageView>();

		if (progressBar == null) {
			progressBar = new ArrayList<ProgressBar>();
		}
		if (picurList == null) {
			picurList = new ArrayList<String>();
		}
		picurList.add(url);

		LayoutInflater mli = LayoutInflater.from(this);
		View vi0 = mli.inflate(R.layout.view_original_image, null);

		listViews.add(vi0);

		ImageView img = (ImageView) vi0.findViewById(R.id.imageview);

		img.setBackgroundColor(0xff000000);
		img.setScaleType(ScaleType.CENTER);
		// LinearLayout.LayoutParams lp = new
		// LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT,
		// LayoutParams.WRAP_CONTENT);
		// lp.gravity = Gravity.CENTER;
		// img.setLayoutParams(lp);

		MyApplication.finalbitmap.display(img, Common.getPublicImagesSmallUrl(url));

		listImaViews.add(img);
		ProgressBar loadimage = (ProgressBar) vi0.findViewById(R.id.loadimage);
		progressBar.add(loadimage);

	}

	private OnPageChangeListener pageChangeListener = new OnPageChangeListener() {

		public void onPageSelected(int arg0) {
			// location = arg0;
			tv_pic_num.setText(arg0 + 1 + "/" + picnum);
			initImagesBig(arg0);
		}

		public void onPageScrolled(int arg0, float arg1, int arg2) {

		}

		public void onPageScrollStateChanged(int arg0) {

		}
	};

	class MyPageAdapter extends PagerAdapter {

		private ArrayList<View> listViews;

		private int size;

		public MyPageAdapter(ArrayList<View> listViews) {
			this.listViews = listViews;
			size = listViews == null ? 0 : listViews.size();
		}

		public void setListViews(ArrayList<View> listViews) {
			this.listViews = listViews;
			size = listViews == null ? 0 : listViews.size();
		}

		public int getCount() {
			return size;
		}

		public int getItemPosition(Object object) {
			return POSITION_NONE;
		}

		public void destroyItem(View arg0, int arg1, Object arg2) {
			((ViewPagerFixed) arg0).removeView(listViews.get(arg1 % size));
		}

		public void finishUpdate(View arg0) {
		}

		public Object instantiateItem(View arg0, int arg1) {
			try {
				((ViewPagerFixed) arg0).addView(listViews.get(arg1 % size), 0);

			} catch (Exception e) {
			}
			return listViews.get(arg1 % size);
		}

		public boolean isViewFromObject(View arg0, Object arg1) {
			return arg0 == arg1;
		}

	}

	private class downloadImage extends AsyncTask<String, Integer, String> {
		private byte[] data;
		int p = 0;

		@SuppressWarnings("unused")
		public downloadImage(int p) {
			super();
			this.p = p;
		}

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
		}

		@Override
		protected void onProgressUpdate(Integer... values) {
			super.onProgressUpdate(values);
			// LordImage.setProgress(values[0]);
		}

		@Override
		protected String doInBackground(String... params) {
			Log.i("doInBackground", params[0]);
			data = QHttpUtil.download_image1(params[0]);
			return null;
		}

		@Override
		protected void onPostExecute(String uri) {
			super.onPostExecute(uri);
			try {
				Bitmap showBitmap = null;
				progressBar.get(p).setVisibility(View.GONE);
				if (data != null) {
					showBitmap = BitmapDecoder.decodeSampledBitmapFromByteArray(data, 0, data.length, mScreenWidth, mScreenHeight);
					(listImaViews.get(p)).setImageBitmap(showBitmap);
				} else {
					Log.w("onPostExecute", "download null data for display image");
				}
				String savpic = MyApplication.FILE_PATH_TEMP + MD5Util.encode(uri) + FileUtils.getImageFileExtension(uri);
				BitmapUtil.saveBmp(showBitmap, savpic, 100);

				if (!new File(savpic).exists()) {
					// Common.tip(this, "图片保存失败");
				}

				DownloadingMap.remove(p);
				PhotoViewAttacher mAttacher = new PhotoViewAttacher((listImaViews.get(p)));
				mAttacher.setOnViewTapListener(new OnViewTapListener() {
					@Override
					public void onViewTap(View view, float x, float y) {
						MorePicShow.this.finish();
					}
				});
				adapter.notifyDataSetChanged();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

	}
}
